﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class Manger_NewsAdd : System.Web.UI.Page
{
    string sMajorID;
    string sMajorName;
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie ck = Request.Cookies["major"];
        if (ck != null)
        {
            sMajorID = ck.Values["majorid"];
            sMajorName = HttpUtility.UrlDecode(ck.Values["majorname"]);
            XmlDataSource1.DataFile = "~/xml/NewsType_" + sMajorID + ".xml";
            if(!IsPostBack){
                tbWriter.Text = HttpUtility.UrlDecode(ck.Values["username"]);
                string newsid = Request.QueryString["news_id"];
                if (newsid !=null)
                {
                    SqlDataSource1.SelectCommand = "select News_Type,News_TypeName,News_MajorID,News_Writer,News_Title,News_From,News_Content from zyk_News where News_ID=@newsid";
                    SqlDataSource1.SelectParameters.Clear();
                    SqlDataSource1.SelectParameters.Add("newsid",TypeCode.Int16,newsid);
                    DataView dv=(DataView) SqlDataSource1.Select(DataSourceSelectArguments.Empty);
                    if(dv.Count>0)
                    {
                        lbTypePath.Text = dv[0]["News_Type"].ToString();
                        tbNewsType.Text = dv[0]["News_TypeName"].ToString();
                        tbTitle.Text = dv[0]["News_Title"].ToString();
                        tbWriter.Text = dv[0]["News_Writer"].ToString();
                        tbFrom.Text = dv[0]["News_From"].ToString();
                        FCKeditor1.Value = dv[0]["News_Content"].ToString();
                        hfType.Value = newsid; //非0表示现在是编辑状态
                    }

                }
            }
                    
        }
        else
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }
    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        
        string sTextPath=TreeView1.SelectedNode.Text;
        string sValuePath = "{"+TreeView1.SelectedNode.Value+"}";
        TreeNode tn=TreeView1.SelectedNode;
        while (tn.Parent != null)
        {
            tn=tn.Parent;
            sTextPath = tn.Text +"->"+ sTextPath;
            sValuePath = "{" + tn.Value + "}" + sValuePath;
        }
        tbNewsType.Text = sTextPath;
        lbTypePath.Text = sValuePath;
        TreeView1.Visible = false;
    }
    protected void btSelect_Click(object sender, EventArgs e)
    {
        TreeView1.Visible = true;
    }
    protected void btNewsAdd_Click(object sender, EventArgs e)
    {
       
        
        //查找内容中是否有图片，如果有则提取地址。
       string sHasImage = "0";
       string sImageURL = getImageURL(FCKeditor1.Value);
       if (sImageURL != "")
           sHasImage = "1" ;
       if (hfType.Value == "0")
       {
           SqlDataSource1.InsertCommand = "insert into [zyk_News]([News_Type],[News_TypeName],[News_MajorID],[News_Title],[News_HasImage],[News_ImageURL],[News_Writer],[News_From],[News_UserID],[News_Content])";
           SqlDataSource1.InsertCommand += " values(@newstype,@newstypename,@newsmajorid,@newstitle,@newshasimage,@newsimageurl,@newswriter,@newsfrom,@newsuserid,@newscontent)";
           SqlDataSource1.InsertParameters.Add("newstype", lbTypePath.Text);
           SqlDataSource1.InsertParameters.Add("newstypename", tbNewsType.Text);
           SqlDataSource1.InsertParameters.Add("newsmajorid", Request.Cookies["major"].Values["majorid"]);
           SqlDataSource1.InsertParameters.Add("newstitle", tbTitle.Text);
           SqlDataSource1.InsertParameters.Add("newshasimage", sHasImage);
           SqlDataSource1.InsertParameters.Add("newsimageurl", sImageURL);
           SqlDataSource1.InsertParameters.Add("newswriter", tbWriter.Text);
           SqlDataSource1.InsertParameters.Add("newsfrom", tbFrom.Text);
           SqlDataSource1.InsertParameters.Add("newsuserid", Page.User.Identity.Name);
           SqlDataSource1.InsertParameters.Add("newscontent", FCKeditor1.Value);
           SqlDataSource1.Insert();
       }
       else
       {
           SqlDataSource1.UpdateCommand = "update [zyk_News] set News_Type=@newstype,News_TypeName=@newstypename,News_Title=@newstitle,News_HasImage=@newshasimage,";
           SqlDataSource1.UpdateCommand += " News_ImageURL=@newsimageurl,News_Writer=@newswriter,News_From=@newsfrom,News_Content=@newscontent ";
           SqlDataSource1.UpdateCommand += "where News_ID=@newsid";
           SqlDataSource1.UpdateParameters.Add("newstype", lbTypePath.Text);
           SqlDataSource1.UpdateParameters.Add("newstypename", tbNewsType.Text);
           SqlDataSource1.UpdateParameters.Add("newstitle", tbTitle.Text);
           SqlDataSource1.UpdateParameters.Add("newshasimage", sHasImage);
           SqlDataSource1.UpdateParameters.Add("newsimageurl", sImageURL);
           SqlDataSource1.UpdateParameters.Add("newswriter", tbWriter.Text);
           SqlDataSource1.UpdateParameters.Add("newsfrom", tbFrom.Text);
           SqlDataSource1.UpdateParameters.Add("newsuserid", Page.User.Identity.Name);
           SqlDataSource1.UpdateParameters.Add("newscontent", FCKeditor1.Value);
           SqlDataSource1.UpdateParameters.Add("newsid", TypeCode.Int32, hfType.Value);
           SqlDataSource1.Update();
       }
    }
    /// <summary>
    /// 利用正则表达式从内容中获得第一个图片地址。
    /// </summary>
    /// <param name="sContent"></param>
    /// <returns></returns>
    public string getImageURL(string sContent)
    {
        string sImageReg = "<IMG[^<>s]*src=\"([^\"'>]*)\"[^>]*>";
        string sImageURL = "";
        Match match = Regex.Match(sContent, sImageReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
        if (match.Success)
        {
            sImageURL = match.Groups[1].Value;
        }
        return sImageURL;
    }
    protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        if (e.AffectedRows == 1)
        {
            //如果连续添加选项打钩了。
            if (cbContinue.Checked == true)
            {
                FCKeditor1.Value = "";
                tbFrom.Text = "";
                tbTitle.Text = "";
                Response.Write("<script >function window.onload() {alert('文章添加成功!');}</script>");
            }
            //没打钩就进入管理。
            else
                Response.Redirect("Manger_NewsList.aspx");
            
        }
        else
        {
            Response.Write("<script >function window.onload() {alert('文章添加失败，请检查数据!');}</script>");
        }
    }
    protected void SqlDataSource1_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
        if (e.AffectedRows == 1)
        {
            Response.Write("<script >function window.onload() {alert('文章更新成功!');}</script>");

        }
        else
        {
            Response.Write("<script >function window.onload() {alert('文章更新失败，请检查数据!');}</script>");
        }
    }
}
